<template>
  <div class="image-tools">
    <ToolContainer
      tool-name="图片处理"
      default-tab="compress"
      @tab-change="handleTabChange"
    >
      <template #tabs>
        <!-- 图片压缩标签页 -->
        <el-tab-pane label="图片压缩" name="compress">
          <ToolSection
            show-upload
            upload-text="拖拽图片到此处或点击上传"
            upload-tip="支持JPG、PNG、WebP等格式"
            :upload-icon="UploadFilled"
            accept="image/*"
            @file-change="handleImageChange"
          >
            <template #preview>
              <div v-if="imageUrl" class="image-preview">
                <img :src="imageUrl" alt="预览图" />
                <div class="image-info">
                  <p><strong>原始大小：</strong>{{ originalSize }}</p>
                  <p><strong>压缩后大小：</strong>{{ compressedSize }}</p>
                </div>
              </div>
            </template>

            <template #options>
              <div v-if="imageUrl" class="compress-options">
                <el-form label-width="100px">
                  <el-form-item label="压缩质量">
                    <el-slider
                      v-model="quality"
                      :min="0"
                      :max="100"
                      :step="1"
                      show-input
                      :format-tooltip="formatQuality"
                    />
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="handleCompress" 
                :loading="loading"
                :disabled="!imageUrl"
              >
                压缩
              </el-button>
              <el-button 
                type="success" 
                @click="handleDownload" 
                :loading="loading"
                :disabled="!processedBlob"
              >
                下载
              </el-button>
            </template>
          </ToolSection>
        </el-tab-pane>
        
        <!-- 格式转换标签页 -->
        <el-tab-pane label="格式转换" name="convert">
          <ToolSection
            show-upload
            upload-text="拖拽图片到此处或点击上传"
            upload-tip="支持JPG、PNG、WebP、GIF等格式"
            :upload-icon="UploadFilled"
            accept="image/*"
            @file-change="handleImageChange"
          >
            <template #preview>
              <div v-if="imageUrl" class="image-preview">
                <img :src="imageUrl" alt="预览图" />
              </div>
            </template>

            <template #options>
              <div v-if="imageUrl" class="convert-options">
                <el-form label-width="100px">
                  <el-form-item label="目标格式">
                    <el-select v-model="targetFormat" placeholder="选择目标格式">
                      <el-option label="PNG" value="png" />
                      <el-option label="JPEG" value="jpeg" />
                      <el-option label="WebP" value="webp" />
                      <el-option label="GIF" value="gif" />
                    </el-select>
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="handleConvert" 
                :loading="loading"
                :disabled="!imageUrl"
              >
                转换
              </el-button>
              <el-button 
                type="success" 
                @click="handleDownload" 
                :loading="loading"
                :disabled="!processedBlob"
              >
                下载
              </el-button>
            </template>
          </ToolSection>
        </el-tab-pane>
        
        <!-- 添加水印标签页 -->
        <el-tab-pane label="添加水印" name="watermark">
          <ToolSection
            show-upload
            upload-text="拖拽图片到此处或点击上传"
            upload-tip="支持JPG、PNG等格式"
            :upload-icon="UploadFilled"
            accept="image/*"
            @file-change="handleImageChange"
          >
            <template #preview>
              <div v-if="imageUrl" class="image-preview">
                <img :src="imageUrl" alt="预览图" />
              </div>
            </template>

            <template #options>
              <div v-if="imageUrl" class="watermark-options">
                <el-form label-width="100px">
                  <el-form-item label="水印文字">
                    <el-input v-model="watermarkText" placeholder="输入水印文字" />
                  </el-form-item>
                  <el-form-item label="水印颜色">
                    <el-color-picker v-model="watermarkColor" />
                  </el-form-item>
                  <el-form-item label="透明度">
                    <el-slider
                      v-model="watermarkOpacity"
                      :min="0"
                      :max="100"
                      :step="1"
                      show-input
                    />
                  </el-form-item>
                  <el-form-item label="字体大小">
                    <el-slider
                      v-model="watermarkFontSize"
                      :min="12"
                      :max="100"
                      :step="1"
                      show-input
                    />
                  </el-form-item>
                  <el-form-item label="旋转角度">
                    <el-slider
                      v-model="watermarkRotation"
                      :min="-180"
                      :max="180"
                      :step="1"
                      show-input
                    />
                  </el-form-item>
                  <el-form-item label="水印位置">
                    <el-select v-model="watermarkPosition" placeholder="选择水印位置">
                      <el-option label="左上角" value="top-left" />
                      <el-option label="上中" value="top-center" />
                      <el-option label="右上角" value="top-right" />
                      <el-option label="左中" value="middle-left" />
                      <el-option label="居中" value="center" />
                      <el-option label="右中" value="middle-right" />
                      <el-option label="左下角" value="bottom-left" />
                      <el-option label="下中" value="bottom-center" />
                      <el-option label="右下角" value="bottom-right" />
                      <el-option label="平铺" value="tile" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="平铺间距" v-if="watermarkPosition === 'tile'">
                    <el-slider
                      v-model="tileSpacing"
                      :min="50"
                      :max="300"
                      :step="10"
                      show-input
                    />
                  </el-form-item>
                  <el-form-item label="水印数量">
                    <el-input-number
                      v-model="watermarkCount"
                      :min="1"
                      :max="20"
                      :step="1"
                    />
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="handleAddWatermark" 
                :loading="loading"
                :disabled="!imageUrl || !watermarkText.trim()"
              >
                添加水印
              </el-button>
              <el-button 
                type="success" 
                @click="handleDownload" 
                :loading="loading"
                :disabled="!processedBlob"
              >
                下载
              </el-button>
              <el-button 
                type="info" 
                @click="handlePreviewWatermark" 
                :loading="loading"
                :disabled="!imageUrl || !watermarkText.trim()"
              >
                预览效果
              </el-button>
            </template>
          </ToolSection>
        </el-tab-pane>
      </template>
    </ToolContainer>

    <!-- 功能介绍组件 -->
    <FeatureIntro
      :title="featureConfig.title"
      :description="featureConfig.description"
      :header-icon="featureConfig.headerIcon"
      :features="featureConfig.features"
      :initial-visible="showIntro"
      @close="showIntro = false"
    />
  </div>
</template>

<script>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import ToolContainer from '@/components/ToolContainer.vue'
import ToolSection from '@/components/ToolSection.vue'
import FeatureIntro from '@/components/FeatureIntro.vue'
import { featuresConfig } from '@/config/featuresConfig.js'

export default {
  name: 'ImageTools',
  components: {
    UploadFilled,
    ToolContainer,
    ToolSection,
    FeatureIntro
  },
  setup() {
    const loading = ref(false)
    const showIntro = ref(true)
    const imageUrl = ref('')
    const originalSize = ref('')
    const compressedSize = ref('')
    const quality = ref(80)
    const targetFormat = ref('png')
    const watermarkText = ref('')
    const watermarkColor = ref('#000000')
    const watermarkOpacity = ref(50)
    const watermarkFontSize = ref(20)
    const watermarkRotation = ref(0)
    const watermarkPosition = ref('center')
    const tileSpacing = ref(100)
    const watermarkCount = ref(1)
    const currentFile = ref(null)
    const processedBlob = ref(null)

    const formatQuality = (val) => {
      return `${val}%`
    }

    const handleTabChange = (tabName) => {
      console.log('切换到标签页:', tabName)
    }

    const handleImageChange = (file) => {
      if (!file) return
      
      const isImage = file.raw.type.startsWith('image/')
      if (!isImage) {
        ElMessage.error('请上传图片文件')
        return
      }

      const reader = new FileReader()
      reader.onload = (e) => {
        imageUrl.value = e.target.result
        originalSize.value = formatFileSize(file.raw.size)
        currentFile.value = file.raw
      }
      reader.readAsDataURL(file.raw)
    }

    const formatFileSize = (bytes) => {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }

    const handleCompress = async () => {
      if (!imageUrl.value) {
        ElMessage.warning('请先上传图片')
        return
      }
      loading.value = true
      
      try {
        const compressedBlob = await compressImage(imageUrl.value, quality.value / 100)
        compressedSize.value = formatFileSize(compressedBlob.size)
        
        // 更新预览图片
        const compressedUrl = URL.createObjectURL(compressedBlob)
        imageUrl.value = compressedUrl
        processedBlob.value = compressedBlob
        
        loading.value = false
        ElMessage.success('压缩完成')
      } catch (error) {
        loading.value = false
        ElMessage.error('压缩失败：' + error.message)
      }
    }

    const handleConvert = async () => {
      if (!imageUrl.value) {
        ElMessage.warning('请先上传图片')
        return
      }
      loading.value = true
      
      try {
        const convertedBlob = await convertImageFormat(imageUrl.value, targetFormat.value)
        
        // 更新预览图片
        const convertedUrl = URL.createObjectURL(convertedBlob)
        imageUrl.value = convertedUrl
        processedBlob.value = convertedBlob
        
        loading.value = false
        ElMessage.success('转换完成')
      } catch (error) {
        loading.value = false
        ElMessage.error('转换失败：' + error.message)
      }
    }

    const handleAddWatermark = async () => {
      if (!imageUrl.value) {
        ElMessage.warning('请先上传图片')
        return
      }
      if (!watermarkText.value) {
        ElMessage.warning('请输入水印文字')
        return
      }
      loading.value = true
      
      try {
        const watermarkedBlob = await addWatermark(
          imageUrl.value, 
          watermarkText.value, 
          watermarkColor.value, 
          watermarkOpacity.value / 100,
          watermarkFontSize.value,
          watermarkRotation.value,
          watermarkPosition.value,
          tileSpacing.value,
          watermarkCount.value
        )
        
        // 更新预览图片
        const watermarkedUrl = URL.createObjectURL(watermarkedBlob)
        imageUrl.value = watermarkedUrl
        processedBlob.value = watermarkedBlob
        
        loading.value = false
        ElMessage.success('水印添加完成')
      } catch (error) {
        loading.value = false
        ElMessage.error('水印添加失败：' + error.message)
      }
    }

    const handleDownload = () => {
      if (!processedBlob.value) {
        ElMessage.warning('请先处理图片')
        return
      }
      
      const url = URL.createObjectURL(processedBlob.value)
      const a = document.createElement('a')
      a.href = url
      a.download = `processed_image.${targetFormat.value}`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
      
      ElMessage.success('下载成功')
    }

    const handlePreviewWatermark = () => {
      if (!imageUrl.value) {
        ElMessage.warning('请先上传图片')
        return
      }
      // 实现预览水印效果的逻辑
      ElMessage.success('水印预览功能尚未实现')
    }

    // 图片压缩函数
    async function compressImage(imageUrl, quality) {
      return new Promise((resolve, reject) => {
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        const img = new Image()
        
        img.onload = () => {
          canvas.width = img.width
          canvas.height = img.height
          
          ctx.drawImage(img, 0, 0)
          
          canvas.toBlob((blob) => {
            if (blob) {
              resolve(blob)
            } else {
              reject(new Error('压缩失败'))
            }
          }, 'image/jpeg', quality)
        }
        
        img.onerror = () => reject(new Error('图片加载失败'))
        img.src = imageUrl
      })
    }

    // 图片格式转换函数
    async function convertImageFormat(imageUrl, format) {
      return new Promise((resolve, reject) => {
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        const img = new Image()
        
        img.onload = () => {
          canvas.width = img.width
          canvas.height = img.height
          
          // 如果转换为JPG，先填充白色背景
          if (format === 'jpg' || format === 'jpeg') {
            ctx.fillStyle = '#FFFFFF'
            ctx.fillRect(0, 0, canvas.width, canvas.height)
          }
          
          ctx.drawImage(img, 0, 0)
          
          const mimeType = format === 'jpg' ? 'image/jpeg' : `image/${format}`
          canvas.toBlob((blob) => {
            if (blob) {
              resolve(blob)
            } else {
              reject(new Error('格式转换失败'))
            }
          }, mimeType, 0.9)
        }
        
        img.onerror = () => reject(new Error('图片加载失败'))
        img.src = imageUrl
      })
    }

    // 添加水印函数
    async function addWatermark(imageUrl, text, color, opacity, fontSize, rotation, position, spacing, count) {
      return new Promise((resolve, reject) => {
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        const img = new Image()
        
        img.onload = () => {
          canvas.width = img.width
          canvas.height = img.height
          
          // 绘制原图
          ctx.drawImage(img, 0, 0)
          
          // 设置水印样式
          ctx.font = `${fontSize}px Arial`
          ctx.fillStyle = color
          ctx.globalAlpha = opacity
          ctx.textAlign = 'center'
          ctx.textBaseline = 'middle'
          
          // 添加文字阴影效果
          ctx.shadowColor = 'rgba(0, 0, 0, 0.3)'
          ctx.shadowBlur = 2
          ctx.shadowOffsetX = 1
          ctx.shadowOffsetY = 1
          
          // 根据位置和数量绘制水印
          if (position === 'tile') {
            // 平铺水印
            drawTiledWatermark(ctx, text, canvas.width, canvas.height, spacing, rotation)
          } else {
            // 单个或多个水印
            const positions = getWatermarkPositions(position, canvas.width, canvas.height, count)
            positions.forEach(pos => {
              drawSingleWatermark(ctx, text, pos.x, pos.y, rotation)
            })
          }
          
          canvas.toBlob((blob) => {
            if (blob) {
              resolve(blob)
            } else {
              reject(new Error('水印添加失败'))
            }
          }, 'image/png')
        }
        
        img.onerror = () => reject(new Error('图片加载失败'))
        img.src = imageUrl
      })
    }

    // 绘制单个水印
    function drawSingleWatermark(ctx, text, x, y, rotation) {
      ctx.save()
      ctx.translate(x, y)
      ctx.rotate((rotation * Math.PI) / 180)
      ctx.fillText(text, 0, 0)
      ctx.restore()
    }

    // 绘制平铺水印
    function drawTiledWatermark(ctx, text, width, height, spacing, rotation) {
      const cols = Math.ceil(width / spacing)
      const rows = Math.ceil(height / spacing)
      
      for (let i = 0; i <= cols; i++) {
        for (let j = 0; j <= rows; j++) {
          const x = i * spacing
          const y = j * spacing
          if (x < width && y < height) {
            drawSingleWatermark(ctx, text, x, y, rotation)
          }
        }
      }
    }

    // 获取水印位置
    function getWatermarkPositions(position, width, height, count) {
      const positions = []
      const margin = 50 // 边距
      
      switch (position) {
        case 'top-left':
          for (let i = 0; i < count; i++) {
            positions.push({ x: margin + i * 100, y: margin })
          }
          break
        case 'top-center':
          for (let i = 0; i < count; i++) {
            positions.push({ x: width / 2 + (i - Math.floor(count / 2)) * 100, y: margin })
          }
          break
        case 'top-right':
          for (let i = 0; i < count; i++) {
            positions.push({ x: width - margin - i * 100, y: margin })
          }
          break
        case 'middle-left':
          for (let i = 0; i < count; i++) {
            positions.push({ x: margin, y: height / 2 + (i - Math.floor(count / 2)) * 80 })
          }
          break
        case 'center':
          for (let i = 0; i < count; i++) {
            positions.push({ 
              x: width / 2 + (i - Math.floor(count / 2)) * 120, 
              y: height / 2 
            })
          }
          break
        case 'middle-right':
          for (let i = 0; i < count; i++) {
            positions.push({ x: width - margin, y: height / 2 + (i - Math.floor(count / 2)) * 80 })
          }
          break
        case 'bottom-left':
          for (let i = 0; i < count; i++) {
            positions.push({ x: margin + i * 100, y: height - margin })
          }
          break
        case 'bottom-center':
          for (let i = 0; i < count; i++) {
            positions.push({ x: width / 2 + (i - Math.floor(count / 2)) * 100, y: height - margin })
          }
          break
        case 'bottom-right':
          for (let i = 0; i < count; i++) {
            positions.push({ x: width - margin - i * 100, y: height - margin })
          }
          break
        default:
          positions.push({ x: width / 2, y: height / 2 })
      }
      
      return positions
    }

    return {
      loading,
      showIntro,
      featureConfig: featuresConfig.imageTools,
      imageUrl,
      originalSize,
      compressedSize,
      quality,
      targetFormat,
      watermarkText,
      watermarkColor,
      watermarkOpacity,
      watermarkFontSize,
      watermarkRotation,
      watermarkPosition,
      tileSpacing,
      watermarkCount,
      processedBlob,
      UploadFilled,
      formatQuality,
      handleTabChange,
      handleImageChange,
      handleCompress,
      handleConvert,
      handleAddWatermark,
      handleDownload,
      handlePreviewWatermark
    }
  }
}
</script>

<style scoped>
.image-tools {
  position: relative;
}

.image-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  width: 100%;
}

.image-preview img {
  max-width: 100%;
  max-height: 400px;
  object-fit: contain;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.image-info {
  padding: 16px;
  background: var(--el-bg-color-page, #fafbfc);
  border-radius: 8px;
  border: 1px solid var(--el-border-color-lighter, #f2f6fc);
  text-align: center;
}

.image-info p {
  margin: 8px 0;
  color: var(--el-text-color-primary, #303133);
}

.compress-options,
.convert-options,
.watermark-options {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .image-preview img {
    max-height: 300px;
  }
  
  .image-info {
    padding: 12px;
  }
}
</style> 